<template>
	<div class="content">
		<el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="100px" style="padding: 10px">
			<el-row :gutter="16">
				<el-col :span="12">
					<el-form-item label="计划时间" required prop="planBeginTime">
						<el-date-picker v-model="formData.planBeginTime" type="datetimerange"
														valueFormat="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="计划开始时间"
														end-placeholder="计划结束时间" />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="工厂/车间" required prop="organizationId">
						<el-tree-select v-model="formData.organizationId" check-strictly filterable
														:render-after-expand="false" :data="lineGroup" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="计划类型" required prop="type">
						<el-select v-model="formData.type" placeholder="请输入计划类型">
							<el-option v-for="item in typeData" :key="item.value" :value="item.value"
												 :label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="良率计算" required prop="yield">
						<el-select v-model="formData.yield" placeholder="请选择属性" @change="changeCount">
							<el-option key="1" label="是" :value="true" />
							<el-option key="0" label="否" :value="false" />
						</el-select>
					</el-form-item>
				</el-col>
				<template v-for="(item, index) in formData.keys" :key="index">
					<el-col :span="6">
						<el-form-item label="产品名称" required>
							<el-select v-model="item.productId" placeholder="请选择产品名称" @change="changeProduct(true)"
												 filterable>
								<el-option v-for="i in productData" :key="i.id" :value="i.id"
													 :label="i.productName" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="属性" required>
							<el-select v-model="item.property" placeholder="请选择属性" @change="changeProduct(true)">
								<el-option key="0" label="正常" :value="0" />
								<el-option key="1" label="返工" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="路线名称" required>
							<el-select v-model="item.processRouteId" placeholder="请选择路线名称" filterable
												 @change="changeCount">
								<el-option v-for="i in allRouteData" :key="i.id" :value="i.id"
													 :label="i.processName" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="下发数量" required>
							<el-input v-model="item.planCount" placeholder="请输入下发数量" style="width: 100%"
												@input="changeCount" />
						</el-form-item>
					</el-col>
					<el-col :span="6" v-if="item.gap">
						<el-form-item :label="`原材料缺口`"> {{ item.gap || '--' }}</el-form-item>

					</el-col>
					<el-col :span="12">
						<el-form-item label="">
							<router-link to="/production/production">
								<el-button :icon="ArrowLeft" style="margin-right: 10px">返回
								</el-button>
							</router-link>
							<el-button :icon="Edit" type="primary" @click="handleSave(ruleFormRef,true)"
												 v-if="formData.status != 1">保存并新建
							</el-button>
							<el-button :icon="Edit" type="primary" @click="handleSave(ruleFormRef)"
												 v-if="formData.status != 1">保存
							</el-button>
						</el-form-item>
					</el-col>
				</template>

			</el-row>

		</el-form>
		<Resource v-if="!!pageId" :processName="processName" :pageId="pageId" :cachedData="cachedData"></Resource>
	</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import axiosInstance from '@/utils/http/api';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseDataPlanData } from '@/hooks/production/productionPlan';
import { allRouteApi, lineAll, ProductionPlanDetailApi } from '@/api/production/productionPlan';


import { ArrowLeft, Edit } from '@element-plus/icons-vue';
import Resource from './components/resource/index.vue';
import { useRoute, useRouter } from 'vue-router';

const {
	searchParam,
	pageSize,
	current,
	pageTotal,
	paginatedData,
	searchFields,
	productData,
	// allRouteData,
	materialData,
	lineListAll,
	typeData,
	lineGroup,
	handleAddSubmit,
	handleSearch,
	handleSizeChange,
	handleCurrentChange,
	addBaseDataPlan,
	deleteBaseDataPlan,
	handleIssue,
	isLoading
} = useBaseDataPlanData();
const index = ref(0);
const expandedRows = ref([]);
const chartDom = ref({});
const dialogRef = ref(false);
const echartsContainer = ref(null);
const allRouteData = ref([]);

interface RuleForm {
}

const processName = ref('');
const pageId = ref('');
const cachedData = ref([]);

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
	planBeginTime: [
		{ required: true, message: '请选择计划时间', trigger: 'blur' }
	],
	organizationId: [
		{ required: true, message: '请选择工厂/车间', trigger: 'blur' }
	],
	type: [
		{ required: true, message: '请选择计划类型', trigger: 'blur' }
	],
	yield: [
		{ required: true, message: '请选择是否良率计算', trigger: 'blur' }
	]
});
const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	yield: true,
	type: '1',
	keys: [
		{
			productId: '',
			allRouteData: '',
			materialBom: '',
			index: index.value,
			status: 1
		}
	]
});


const onCloseButton = () => {
	dialogRef.value = false;
};
// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};

	// current.value = 1
	getList();
};

const router = useRouter();
const route = useRoute();


const showDialog = (row) => {
	router.push('/production/productionDetail?planNo=' + row.planNo + '&planNoId=' + row.id);

};
const changeProduct = (clearn) => {
	// keysArray(e, index);
	const keys = formData.value.keys[0];
	keys.gap = null;
	if (keys.productId !== undefined && keys.productId !== null
		&& keys.property !== undefined && keys.property !== null && keys.productId !== '') {
		if (clearn) {
			keys.processRouteId = null;
		}
		// keys.allRouteData = [];
		axiosInstance.post('/api/basedataProcessRoute/listProcesssRoute', {
			productId: keys.productId,
			property: keys.property,
			current: 0,
			pageSize: 999999,
			processPublished: 1
		}).then(res => {
			allRouteData.value = res.data.records;
			if (allRouteData.value.length > 0) {
				formData.value.keys[0].processRouteId = allRouteData.value[0].id;
				changeCount();
			} else {
				pageId.value = null;
			}


			// formData.value.keys[0] = {
			//   ...keys,
			//   allRouteData: filteredAllRouteData
			// };
		});
	}
};


// 输入下发数量计算原材料缺口
let timeoutId = null; // 用于存储定时器的ID

const changeCount = () => {
	const keys = formData.value.keys[0];
	console.log(keys.planCount,'keys.planCount');

	pageId.value = keys.processRouteId;
	processName.value = allRouteData.value.find(item => item.id == keys.processRouteId).processName;

	// 清除之前的定时器
	clearTimeout(timeoutId);

	// 设置新的定时器
	timeoutId = setTimeout(() => {
		if (keys.processRouteId && keys.planCount && formData.value.yield) {
			const param = {
				yield: formData.value.yield,
				processRouteId: keys.processRouteId,
				orderCount: keys.planCount
			};
			if (formData.value.id) {
				param.planOrderId = formData.value.id;
			}
			axiosInstance.get('/api/planOrder/queryStorageByRouteId', {
				params: param
			}).then(res => {
				formData.value.keys[0].gap = res.data.count;
			});
		}

		if (keys.processRouteId && formData.value.yield) {
			axiosInstance.post('/api/planDetail/getPlanOrderProcedurePreview', {
				ifYield: formData.value.yield,
				processRouteId: keys.processRouteId,
				planCount: keys.planCount || 0
			}).then(res => {
				if (res.data && res.data.length > 0) {
					cachedData.value = res.data;
				}
			});
		}
	}, 500); // 1秒后执行
};

const keysArray = (e: string, index: number) => {
	const filteredAllRouteData = allRouteData.value.filter((i) => i.productId === e);

	const filteredMaterialBom = materialData.value.filter((i) => i.productId === e);

	formData.value.keys[index] = {
		...formData.value.keys[index],
		productId: e,
		allRouteData: filteredAllRouteData,
		materialBom: filteredMaterialBom
	};

};
const getTypeName = (type: string) => {
	const name = typeData.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};

const typeList = ref([
	{ label: '未完成', value: '0' },
	{ label: '已完成', value: '1' }
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

// 新建记录
const handleAdd = () => {
	isEdit.value = false;
	formData.value = {
		planNo: '',
		name: '',
		keys: [
			{
				productId: '',
				allRouteData: '',
				index: index.value,
				status: 1
			}
		]
	};
	showCrud.value = true;
};

// 编辑记录
const handleEdit = (row: any) => {
	isEdit.value = true;
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {
		formData.value = {
			...row,
			planBeginTime: [row.planBeginTime, row.planEndTime],
			keys: res.data.records
		};
		changeCount();
		res.data.records.map((item: any, index: number) => {
			return keysArray(item.productId, index);
		});
	});

	showCrud.value = true;
};


const handleOver = (row: any) => {
	ElMessageBox.confirm('确定完结该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		axiosInstance.post('/api/planOrder/updateByIdStatus', { id: row.id, status: '1' })
			.then(res => {
				if (res.code === 200) {
					ElMessage.success('操作成功');
					getList();
				} else {
					ElMessage.error(res.message);
				}
			});
	}).catch(() => {
	});
};
// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await deleteBaseDataPlan(row.id);
	}).catch(() => {
	});
};

// 保存记录 计划信息保存
const handleSave = async (formEl: FormInstance | undefined, back) => {
	await formEl.validate((valid, fields) => {
		if (valid) {
			handleAddSubmit(formData.value, (() => {
				// 跳转到/production/production  like：  <router-link to="/production/production">
				//     <el-button :icon="ArrowLeft" style="margin-right: 10px">
				//
				//     </router-link>
				if (!back) {
					router.replace({ path: '/production/production' });
				} else {
					// router.replace({path: '/production/productionAdd'});
					pageId.value = null;
					formData.value = {
						status: '0',
						yield: true,
						type: '1', keys: [
							{
								productId: '',
								allRouteData: '',
								materialBom: '',
								index: index.value,
								status: 1
							}
						]
					};
					getList();
				}
			}));
		}
	});
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row, expanded) => {
	if (expanded) {
		rowChildren(row);
		expandedRows.value.push(row.id);
	} else {
		const index = expandedRows.value.indexOf(row.id);
		if (index > -1) {
			expandedRows.value.splice(index, 1);
		}
	}

	// else {
	//   getList();
	// }
};

const collapseAll = () => {
	expandedRows.value = [];
};


const rowChildren = (row: any) => {
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		paginatedData.value = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data.records };
			}
			return item;
		});
	});
};


const buildTree = (items: any) => {
	const itemMap = {};
	const rootItems = [];
	items.forEach((item) => {
		itemMap[item.id] = {
			...item,
			value: item.id,
			label: item.orgName,
			name: item.orgName,
			children: []
		};
	});
	items.forEach((item) => {
		if (!item.parentId || item.parentId === '0') {
			rootItems.push(itemMap[item.id]);
		} else {
			if (itemMap[item.parentId]) {
				itemMap[item.parentId].children.push(itemMap[item.id]);
			}
		}
	});

	return rootItems;
};

const myTable = ref(null);
// 获取列表
const getList = async () => {
	await lineAll({}).then((res) => {
		lineListAll.value = res.data.records;
		lineGroup.value = buildTree(res.data.records);
		formData.value.organizationId = res.data.records.find(item => item.parentId == 0).id;
	});
	allRouteApi({}).then((res) => {
		allRouteData.value = res.data.records;
		console.log(allRouteData.value);

		axiosInstance.post('/api/planOrder/count', {})
			.then(res => {
				countList.value = res.data;
			});
		if (route.query.id) {
			formData.value = JSON.parse(localStorage.getItem('addFormData'));
			let canDo = false;
			formData.value.keys.map((item: any, index: number) => {
				if (index == formData.value.keys.length - 1) {
					canDo = true;
				}
				return keysArray(item.productId, index);
			});

			if (canDo) {
				changeCount();
				changeProduct();
			}
		}
	});
};


const percentageCompleted = computed(() => {
	const { completedCount, total } = countList.value;
	// 确保总数不为0以避免除以0的错误，并保留一位小数
	return total ? Number(((completedCount / total) * 100).toFixed(1)) : 0;
});


const countList = ref({});

onMounted(() => {
	getList();


});
</script>
<style scoped>
.content {
	background: #fff;
}
</style>
